package com.jsy.user.config;

import com.jsy.common.util.TokenDecode;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    /**
     * 设置公钥的存储
     * @param tokenConverter 令牌转换器
     * @return 令牌信息存储对象
     */
   @Bean
    public JwtTokenStore tokenStore(JwtAccessTokenConverter tokenConverter){
        return new JwtTokenStore(tokenConverter);
    }

    /**
     * 令牌转换器；主要设置在解析令牌的时候的公钥
     * @return
     */
    @Bean
    public JwtAccessTokenConverter tokenConverter(){
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setVerifierKey(TokenDecode.getPubKey());
        return tokenConverter;
    }

    /**
     * 配置资源权限
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/add","/user/load/*").permitAll()
                .anyRequest().authenticated();
    }
}
